/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Generate;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;


/**
 *
 * @author Roderick
 */
public class UtilFile {

    public static Object getProjectXML(String path_xml, Class cls) throws InstantiationException, IllegalAccessException {
        //Project project = null;
        Object ob = cls.newInstance();
        File file = new File(path_xml);
        if (!file.exists()) {
            System.err.println("Fichero XML no existe");
            return null;
        }
        //leer xml
        InputStream is = null;
        Reader reader = null;
        try {
            is = new FileInputStream(path_xml);
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            System.out.println("Reding xml...");
        } catch (Exception ex) {
            System.err.println("Error al leer fichero XML : " + ex);
        }
        //Poblar objecto Project        
        JAXBContext jc;
        try {
            jc = JAXBContext.newInstance(cls);
            Unmarshaller u = jc.createUnmarshaller();
            ob = u.unmarshal(reader);
            System.out.println("Built project...");
        } catch (JAXBException ex) {
            System.err.println("Error al poblar objeto Project : " + ex.toString());
        }
        return ob;
    }

    public static String readFile(String path_file) {
        String file = "";
        Path path = Paths.get(path_file);
        Charset charset = Charset.forName("ISO-8859-1");
        try (BufferedReader reader = Files.newBufferedReader(path, charset)) {
            file = readFileAsString(reader);
        } catch (IOException e) {
            System.err.println("Error: readFile " + e.toString());
        }
        return file;
    }
    
    public static void writefile(String path, String content) {
        Writer output = null;
        
        File file = new File(path );
        try {
            output = new BufferedWriter(new FileWriter(file));
            output.write(content);
            output.close();
        } catch (IOException ex) {
            System.out.println("Error: writefile " +ex.toString());
        }
    }

    public static void writefile(String Name, String path, String Contenido) {
        Writer output = null;
        System.out.println(path + File.separator + Name);
        File file = new File(path + File.separator + Name);
        try {
            //output = new BufferedWriter(new FileWriter(file));
            output = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(file), "UTF8"));
            output.write(Contenido);
            output.close();
        } catch (IOException ex) {
            System.out.println("Error: writefile " +ex.toString());
        }
    }

    protected static String readFileAsString(Reader reader) {
        StringBuffer fileData = new StringBuffer(100000);
        char[] buf = new char[1024];
        int numRead = 0;
        try {
            while ((numRead = reader.read(buf)) != -1) {
                String readData = String.valueOf(buf, 0, numRead);
                fileData.append(readData);
                buf = new char[1024];
            }
            reader.close();
        } catch (IOException ex) {
            System.out.println(ex.toString());
        }
        return fileData.toString();
    }

    public static void copyfile(String srFile, String dtFile) {
        try {


            File f1 = new File(srFile);
            File f2 = new File(dtFile);
            InputStream in = new FileInputStream(f1);

            //For Append the file.
//  OutputStream out = new FileOutputStream(f2,true);

            //For Overwrite the file.
            OutputStream out = new FileOutputStream(f2);

            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
            System.out.println("File copied.");
        } catch (FileNotFoundException ex) {
            System.out.println(ex.getMessage() + " in the specified directory.");
            System.exit(0);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    public static void unzip(String strZipFile, String zipPath) {

        try {
            /*
             * STEP 1 : Create directory with the name of the zip file
             *
             * For e.g. if we are going to extract c:/demo.zip create c:/demo
             * directory where we can extract all the zip entries
             *
             */
            File fSourceZip = new File(strZipFile);
            /*String zipPath = strZipFile.substring(0, strZipFile.length() - 4);
             File temp = new File(zipPath);
             temp.mkdir();
             System.out.println(zipPath + " created");*/

            /*
             * STEP 2 : Extract entries while creating required
             * sub-directories
             *
             */
            ZipFile zipFile = new ZipFile(fSourceZip);
            Enumeration e = zipFile.entries();

            while (e.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) e.nextElement();
                File destinationFilePath = new File(zipPath, entry.getName());



                //if the entry is directory, leave it. Otherwise extract it.
                if (entry.isDirectory()) {
                    //create directories if required.
                    destinationFilePath.mkdirs();
                    continue;
                } else {
                    System.out.println("Extracting " + destinationFilePath);

                    /*
                     * Get the InputStream for current entry
                     * of the zip file using
                     *
                     * InputStream getInputStream(Entry entry) method.
                     */
                    BufferedInputStream bis = new BufferedInputStream(zipFile
                            .getInputStream(entry));

                    int b;
                    byte buffer[] = new byte[1024];

                    /*
                     * read the current entry from the zip file, extract it
                     * and write the extracted file.
                     */
                    FileOutputStream fos = new FileOutputStream(destinationFilePath);
                    BufferedOutputStream bos = new BufferedOutputStream(fos,
                            1024);

                    while ((b = bis.read(buffer, 0, 1024)) != -1) {
                        bos.write(buffer, 0, b);
                    }

                    //flush the output stream and close it.
                    bos.flush();
                    bos.close();

                    //close the input stream.
                    bis.close();
                }
            }
        } catch (IOException ioe) {
            System.out.println("IOError :" + ioe);
        }
    }
    
    public static void createDirectory(String path) {
        File folder = new File(path);
        if (!folder.exists()) {
            folder.mkdirs();
            System.out.println("createDirectory : " + folder.getAbsolutePath());
        }
    }

    
}
